#!/usr/bin/env bash
. ./scripts/devcontainer/_assert-in-container "$0" "$@"

set -euo pipefail

trap ctrl_c INT

function ctrl_c() {
  killall -9 Tests
  exit 1
}

PUBLISHED=false
PUBLISHED_FLAG=

EXPECTO_ARGS=()

for i in "$@"
do
  case "${i}" in
    --published)
      PUBLISHED=true
      PUBLISHED_FLAG=$i
      ;;
    *) EXPECTO_ARGS+=("${i}");;
  esac
done

killall -9 Tests || true

if [[ "$PUBLISHED" == "true" ]]; then
  EXE=Build/out/Tests/Release/net8.0/linux-x64/Tests
  LOCALEXEC=Build/out/LocalExec/Release/net8.0/linux-x64/LocalExec
else
  EXE=Build/out/Tests/Debug/net8.0/Tests
  LOCALEXEC=Build/out/LocalExec/Debug/net8.0/LocalExec
fi


LOGS="${DARK_CONFIG_RUNDIR}/logs"

./scripts/run-pubsub-emulator

# Use random to avoid old items being in the pubsub queue. Use this instead of
# $RANDOM as RANDOM is only 5 digits
RANDOM_VALUE=$(cat /proc/sys/kernel/random/uuid)

grey="\033[1;30m"
reset="\033[0m"


# Delete the database file before running tests
export DARK_CONFIG_DB_NAME=test-data.db
DB_PATH="${DARK_CONFIG_RUNDIR}/${DARK_CONFIG_DB_NAME}"
echo -e "Deleting database file ${grey}(${DB_PATH})${reset}"
rm -f "$DB_PATH"

# Run the migrations before the other servers start
echo -e "Running migrations ${grey}($LOGS/test-migrations.log)${reset}"
cd backend && \
  DARK_CONFIG_TELEMETRY_EXPORTER=none \
  DARK_CONFIG_ROLLBAR_ENABLED=n \
  DARK_CONFIG_QUEUE_PUBSUB_PROJECT_ID=pubsub-test-${RANDOM_VALUE} \
  "${LOCALEXEC}" migrations run > "$LOGS/test-migrations.log" 2>&1
cd ..

# Reload packages

if [[ -v CI ]]; then
  echo "Running backend server"
  ./scripts/run-backend-server $PUBLISHED_FLAG
  echo "Reloading packages"
  ./scripts/build/reload-packages $PUBLISHED_FLAG
else
  echo "Reloading packages"
  ./scripts/build/reload-packages --test $PUBLISHED_FLAG
fi

JUNIT_FILE="${DARK_CONFIG_RUNDIR}/test_results/backend.xml"


COLOURS="256"
SPINNER=
if [[ -v CI ]]; then
  # Expecto needs `--colours 0` or the xml will be invalid
  # https://github.com/haf/expecto/issues/434
  COLOURS="0"
  SPINNER="--no-spinner"
fi

cd backend
DARK_CONFIG_TELEMETRY_EXPORTER=none \
DARK_CONFIG_ROLLBAR_ENABLED=n \
DARK_CONFIG_LAUNCHDARKLY_SDK_API_KEY=none \
DARK_CONFIG_QUEUE_PUBSUB_PROJECT_ID=pubsub-test-${RANDOM_VALUE} \
"${EXE}" ${SPINNER} --colours "${COLOURS}" --junit-summary "${JUNIT_FILE}" "${EXPECTO_ARGS[@]}"
